package com.easybenefit.UUService.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easybeanfit.UUService.commutill.UUDialogUtill;
import com.easybeanfit.UUService.commutill.UUJsonUtil;
import com.easybeanfit.UUService.commutill.UULogUtil;
import com.easybeanfit.UUService.commutill.UUNetUtill;
import com.easybeanfit.UUService.commutill.UUSharedUtil;
import com.easybeanfit.UUService.commutill.UUStrUtil;
import com.easybeanfit.UUService.commutill.UUToastUtil;
import com.easybeanfit.UUService.config.UUConfig;
import com.easybeanfit.UUService.config.UUDict;
import com.easybenefit.UUService.BaseActivity;
import com.easybenefit.UUService.MyApplication;
import com.easybenefit.UUService.R;
import com.easybenefit.UUService.model.HttpCouponBean;
import com.easybenefit.UUService.model.UserInfo;
import com.easybenefit.UUService.myinterface.IActivityInterface;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

/**
 * 修改账号密码
 */
public class UpdateActivity extends BaseActivity implements IActivityInterface, View.OnClickListener {
    private TextView tv_title;//标题
    private Button btn_add;
    private Button btn_back;
    private TextView tv_username;//显示用户名
    private LinearLayout llt_update_username;
    private LinearLayout llt_update_password;
    private Dialog dialog; // 确认提示框
    private Context context;
    private ProgressDialog progressDialog;
    private UserInfo userInfo;
    private MyApplication application;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        initView();
        initData();
        initListener();
    }

    @Override
    public void initData() {
        context = this;
        application= (MyApplication) getApplication();
        userInfo = (UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class);
        tv_title.setText(getText(R.string.update_info));
        tv_username.setText(userInfo.getUsername());
    }

    @Override
    public void initView() {
        tv_title = (TextView) findViewById(R.id.top_title);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_back = (Button) findViewById(R.id.btn_back);
        llt_update_password = (LinearLayout) findViewById(R.id.llt_update_password);
        llt_update_username = (LinearLayout) findViewById(R.id.llt_update_username);
        tv_username = (TextView) findViewById(R.id.tv_username);
    }

    @Override
    public void initListener() {
        btn_back.setOnClickListener(this);
        llt_update_password.setOnClickListener(this);
        llt_update_username.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.llt_update_password:
                showCenterDialog(1);
                break;
            case R.id.llt_update_username:
                showCenterDialog(0);
                break;
        }
    }

    /**
     * @param type 0代表修改用户名 1代表修改密码
     */
    private void showCenterDialog(int type) {
        View view = getLayoutInflater().inflate(R.layout.dialog_set_coupons, null);
        initButton(view, type);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = Gravity.CENTER;
        wl.y = Gravity.CENTER;
        wl.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240,
                getResources().getDisplayMetrics());
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();
    }

    private void initButton(View view, final int type) {
        Button sureBtn, cancelBtn;
        final EditText editText;
        TextView tv_dialog_title;
        sureBtn = (Button) view.findViewById(R.id.sure_btn);
        cancelBtn = (Button) view.findViewById(R.id.cancel_btn);
        editText = (EditText) view.findViewById(R.id.et_code);
        tv_dialog_title = (TextView) view.findViewById(R.id.tv_dialog_title);
        if (type == 0) {
            tv_dialog_title.setText(getText(R.string.update_username));
            editText.setHint("请输入新账号");
        } else {
            tv_dialog_title.setText(getText(R.string.update_password));
            editText.setHint("请输入新密码");
            int inputType=InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
            editText.setInputType(inputType);
        }
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String result = editText.getText().toString().trim();
                if (!UUStrUtil.isEmpty(result)) {
                    if (result.length()>20){
                        UUToastUtil.showToast(context,"长度不能超过20个字符");
                        return;
                    }
                    String user_id = userInfo.getUser_id();
                    if (type == 0) {
                        if (result.equals(userInfo.getUsername())){
                            UUToastUtil.showToast(context,"新旧用户名不能相同");
                            return;
                        }
                        submit(user_id, "username", result, "meruseredit");

                    } else {
                        if (result.equals(userInfo.getPassword())){
                            UUToastUtil.showToast(context,"新旧密码名不能相同");
                            return;
                        }
                        submit(user_id, "password", result, "merpswdedit");
                    }
                } else {
                    if (type == 0) {
                        UUToastUtil.showToast(context, "用户名不允许为空");
                    } else {
                        UUToastUtil.showToast(context, "密码不允许为空");
                    }

                }
                dialog.dismiss();
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param userid 用户id
     * @param key    参数key值 username or password
     * @param value  参数value值 username or password
     */
    public void submit(String userid, String key, String value, String lasturl) {
        String url = UUConfig.SERVER_BASE_URL + lasturl;

        RequestParams params = new RequestParams();
        params.put("user_id", userid);
        params.put(key, value);
        if (!UUNetUtill.isConnected(context)) {
            UUToastUtil.showToast(context, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(context, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    UULogUtil.e("content", content);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    UUToastUtil.showToast(context, new String(http.getMessage()));
                    dialog.dismiss();
                    application.clearActivity();
                    Intent intent=new Intent(context,LoginActivity.class);
                    startActivity(intent);
                    UUSharedUtil.getDefaultSharedPreferences(context).edit().clear().commit();

                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }
}
